/*
 * main.cpp
 *
 *  Created on: 23/11/2011
 *      Author: Aeradon
 */

#include "IOController.h"

#include <SDL2/SDL.h>

#include <cstdlib>
#include <csignal>
#include <cstdio>
#include <sstream>

IOController *ioController;

/*
 * SIGABRT	Abnormal termination of the program, such as a call to abort
 * SIGFPE	An erroneous arithmetic operation, such as a divide by zero or an operation resulting in overflow.
 * SIGILL	Detection of an illegal instruction
 * SIGINT	Receipt of an interactive attention signal.
 * SIGSEGV	An invalid access to storage.
 * SIGTERM	A termination request sent to the program.
 */

void signalHandler( int signum )
{
    std::stringstream message;
    message << "Interrupt signal (" << signum << ") received\n";

    switch(signum)
    {
		case SIGABRT:
			message << "SIGABRT: Abnormal termination of the program, such as a call to abort";
		break;
		case SIGFPE :
			message << "SIGFPE: An erroneous arithmetic operation, such as a divide by zero or an operation resulting in overflow";
		break;
		case SIGILL :
			message << "SIGILL: Detection of an illegal instruction";
		break;
		case SIGINT :
			message << "SIGINT: Receipt of an interactive attention signal.";
		break;
		case SIGSEGV:
			message << "SIGSEGV: An invalid access to storage";
		break;
		case SIGTERM:
			message << "SIGTERM: A termination request sent to the program";
		break;
    }
    message << "\nSDL_ERROR: " << SDL_GetError();
	fprintf(stderr,"\n%s\n",message.str().c_str());
	fflush(stderr);

    // cleanup and close up stuff here
    // terminate program
    delete(ioController);
    fflush(stdout); fflush(stderr);

    exit(signum);
}

#ifndef __ANDROID__
#undef main
#endif

#ifdef __cplusplus
extern "C"
#endif
int main(int argc, char **argv)
{
	// Register signal callbacks
	signal(SIGABRT, signalHandler);
	signal(SIGFPE,  signalHandler);
	signal(SIGILL,  signalHandler);
	signal(SIGINT,  signalHandler);
	signal(SIGSEGV, signalHandler);
	signal(SIGTERM, signalHandler);

	// Run the renderer
	ioController = new IOController();
	ioController->Initialize();
	ioController->Run();
	delete ioController;

	exit(0);
}

